package org.anti996.learn.mybatis.data;

import org.anti996.learn.mybatis.model.Account;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;

public class DataService implements AccountMapper {
    public static SqlSessionFactory sqlSessionFactory_;

    static {
        String resource = "mybatis-config.xml";
        try (var inputStream = Resources.getResourceAsStream(resource)) {
            sqlSessionFactory_ = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public Account selectAccount(String username) {
        Account account = null;
        try (var session = sqlSessionFactory_.openSession(ExecutorType.REUSE)) {
            var mapper = session.getMapper(AccountMapper.class);
            account = mapper.selectAccount(username);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return account;
    }
}
